package com.hbnu.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author kittychen
 * @since 2025-10-30 19:17
 */
public class UdpSendDemo01 {

    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
            // 1、创建socket
            datagramSocket = new DatagramSocket(1234);

            // 2、创建数据，并将数据封装到数据报包中
            byte[] data = "hello, udp".getBytes();
            DatagramPacket datagramPacket = new DatagramPacket(data, data.length,
                    InetAddress.getByName("127.0.0.1"), 8888);

            // 3、通过socket发送数据包
            datagramSocket.send(datagramPacket);
            System.out.println("数据发送完毕");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 4、关闭资源
            if (datagramSocket != null) {
                datagramSocket.close();
            }
        }
    }
}
